﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Warehouse.Application.Dto.Input;
using Warehouse.Application.Dto.Output;
using Warehouse.Domain.Entities;
using Warehouse.Infrastructure.Repositories;
using Warehouse.Result;
using Yitter.IdGenerator;

namespace Warehouse.Application.Services.Storagelocation
{
    public class StoragelocationAppService: IStoragelocationAppService
    {
        private readonly IMapper _mapper;
        private readonly IWarehouseModelRepository<StorageLocationModel> _storageLocationModelRepository;
        private readonly IWarehouseModelRepository<StorageModel> _storageModelRepository;
        private readonly ILogger<StoragelocationAppService> _logger;

        public StoragelocationAppService(IMapper mapper, IWarehouseModelRepository<StorageLocationModel> storageLocationModelRepository, IWarehouseModelRepository<StorageModel> storageModelRepository, ILogger<StoragelocationAppService> logger)
        {
            _mapper = mapper;
            _storageLocationModelRepository = storageLocationModelRepository;
            _storageModelRepository = storageModelRepository;
            _logger = logger;
        }


        /// <summary>
        /// 添加库位设置
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ApiResult<int> CreateStoragelocation(CreateStoragelocationInput input)
        {
            var model =_mapper.Map<StorageLocationModel>(input);
            model.Id = YitIdHelper.NextId();
            model.CreatedAt = DateTime.Now.Date;
            // 获取当前日期并格式化为yyyyMMdd
            string dateStr = DateTime.Now.ToString("yyyyMMdd");

            // 查询当天已有的记录数
            string prefix = "SO" + dateStr;
            var todayItems = _storageLocationModelRepository.GetValue()
                .Where(x => x.StorageLocationCoding != null &&
                            x.StorageLocationCoding.StartsWith(prefix) &&
                            x.CreatedAt.Date == DateTime.Now.Date)
                .ToList();

            // 计算序号
            int sequence = todayItems.Count + 1;

            // 生成编码
            string coding = $"{prefix}{sequence:D4}";
            model.StorageLocationCoding = coding;


            _storageLocationModelRepository.Create(model);
            _logger.LogInformation("添加库位设置:" + model.Id);
            return new ApiResult<int>()
            {
                Code = ApiEnum.Ok,
                Message = "添加成功",
                Data = 1
            };
        }


        /// <summary>
        /// 获取库位设置
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ApiPaing<GetStoragelocationOutput> GetStoragelocation(PageInput input)
        {
            var StorageLocation =_storageLocationModelRepository.GetValue().Where(x => x.IsDeleted == false);
            var Storage =_storageModelRepository.GetValue().Where(x => x.IsDeleted == false);

            var linq =from a in StorageLocation join
                      b in Storage on  a.StorageId equals b.Id
                      select new GetStoragelocationOutput()
                      {
                          Id = a.Id,
                          StorageLocationCoding = a.StorageLocationCoding,
                          StorageLocationName = a.StorageLocationName,
                          StorageId = a.StorageId,
                          StorageName = b.StorageName,
                          StorageLocationDescribe = a.StorageLocationDescribe,
                      };

            var model =linq.OrderByDescending(x => x.Id).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList();
            return new ApiPaing<GetStoragelocationOutput>
            {
                TotalCount = linq.Count(),
                PageDatas = model,
                Code = ApiEnum.Ok,
                Message = "成功"
            };

        }


        /// <summary>
        /// 删除库位设置
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ApiResult<int> DeleteStoragelocation(long Id)
        {
            var list = _storageLocationModelRepository.GetValue().FirstOrDefault(x => x.Id == Id && x.IsDeleted == false);
            if (list == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.Fail,
                    Message = "未找到该数据"
                };
            }
            list.IsDeleted = true;
            _storageLocationModelRepository.Update(list);
            _logger.LogError("删除了仓库：" + Id);
            return new ApiResult<int>
            {
                Code = ApiEnum.Ok,
                Message = "删除成功",
                Data = 1
            };
        }



        /// <summary>
        /// 修改库区    
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateStoragelocation(UpdateStoragelocationInput input)
        {
            var list = _storageLocationModelRepository.GetValue().FirstOrDefault(x => x.Id == input.Id);
            if (list == null)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.Fail,
                    Message = "未找到该数据"
                };
            }
            var model = _mapper.Map(input, list);
            _storageLocationModelRepository.Update(model);
            return new ApiResult<int>
            {
                Code = ApiEnum.Ok,
                Message = "修改成功",
                Data = 1
            };
        }


        /// <summary>
        /// 获取库区
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
         public ApiResult<StorageLocationModel> GetModelWareHouse(long Id)
        {
            var list = _storageLocationModelRepository.GetValue().FirstOrDefault(x => x.Id == Id && x.IsDeleted == false);
            if (list == null)
            {
                return new ApiResult<StorageLocationModel>
                {
                    Code = ApiEnum.Fail,
                    Message = "未找到该数据"
                };
            }
            return new ApiResult<StorageLocationModel>
            {
                Code = ApiEnum.Ok,
                Message = "成功",
                Data = list
            };
        }


        /// <summary>
        /// 获取所有货架
        /// </summary>
        /// <returns></returns>
        public ApiPaing<StorageModel> ListStorage()
        {
            var list =_storageModelRepository.GetValue().Where(x => x.IsDeleted == false).ToList();
            return new ApiPaing<StorageModel>
            {
                TotalCount = list.Count(),
                PageDatas = list,
                Code = ApiEnum.Ok,
                Message = "成功"
            };
        }



    }
}
